<template>
  <div class="app-container">

    <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd" class="mb20">新增</el-button>

    <el-table v-loading="loading" :data="roleList" border>
      <el-table-column type="selection" width="100" align="center" />
      <el-table-column label="角色编号" align="center" prop="Id" width="120" />
      <el-table-column label="角色名称" align="center" prop="RoleCode" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="描述" align="center" prop="RoleName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="状态" align="center" width="150">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.Status=='1'" type="success" size="small">可用</el-tag>
          <el-tag v-else type="info" size="small">不可用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" prop="CreateOn" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="350">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="primary" icon="el-icon-circle-check" @click="handleDataScope(scope.row)">权限分配</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="RoleCode">
          <el-input v-model="form.RoleCode" placeholder="请输入角色名称" />
        </el-form-item>
         <el-form-item label="状态">
              <el-radio v-model="form.Status" :label="1">可用</el-radio>
              <el-radio v-model="form.Status" :label="0">不可用</el-radio>
            </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form.RoleName" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 权限绑定对话框 -->
    <el-dialog :visible.sync="MenuOpen" :title="MenuTitle" width="500px" :close-on-click-modal="false" @close="treecancel">
      <div class="tree-container" v-loading="menuLoading">
        <el-tree :data="MenuTreeData" show-checkbox node-key="id"  class="custom-tree mt-10" :props="treeProps" default-expand-all ref="permTree" ></el-tree>
      </div>
      <el-row slot="footer">
        <el-button @click="treecancel">取消</el-button>
        <el-button type="primary" @click="submitRolePerm">提交</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {  getAllMenu, getPermissionIdByRoleId,UpdatePermission } from "@/api/menu";
import {getAllRoleList, addRoleModel,updateRole} from "@/api/system/role";

export default {
  name: "Role",
  data () {
    return {
      // 权限分配对话框相关
      MenuOpen: false,
      MenuTitle: '分配权限',
      // 当前编辑中的角色
      currentRole: {},
      // 总权限树
      MenuTreeData: [],
      // 树结构参数
      treeProps: {
        label: 'title',
        children: 'children'
      },
      // 获取角色已有权限标记位
      menuLoading: false,

      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
     // 表单参数
      form: {
        Id: undefined,
        RoleCode: undefined,
        RoleName: undefined,
        Status: "0",
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created () {
    this.getList();
    this.getAllMenus()
  },
  methods: {
    /** 查询角色列表 */
    getList () {
      this.loading = true;
      getAllRoleList({
        pageIndex: 1,
        pageSize: 50
      }).then(
        response => {
          const res = response.data;
          this.roleList = res.data;
          this.total = res.dataCount;
          this.loading = false;
        }
      ).catch(() => {
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect () {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    /** 查询部门树结构 */
    getDeptTreeselect () {
      deptTreeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys () {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys () {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect (roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    /** 根据角色ID查询部门树结构 */
    getRoleDeptTreeselect (roleId) {
      return roleDeptTreeselect(roleId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    // 角色状态修改
    handleStatusChange (row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.roleName + '"角色吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function () {
          return changeRoleStatus(row.roleId, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    treecancel() {
      this.MenuOpen =false
      this.$refs.permTree.setCheckedKeys([]);
    },
    // 表单重置
    reset () {
        this.form={
        Id: undefined,
        RoleCode: undefined,
        RoleName: undefined,
        Status: "0",
      }
      this.resetForm("form");  //重置表单
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
       this.form = JSON.parse(JSON.stringify(row)); //利用JSON进行深拷贝
      this.open = true;
      this.title = "修改角色";
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange (value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 分配数据权限操作 */
    handleDataScope (row) {
      Object.assign(this.currentRole, row)
      this.MenuTitle = `分配 ${this.currentRole.RoleName} 角色权限`
      this.MenuOpen = true
      this.menuLoading = true
      getPermissionIdByRoleId(this.currentRole.Id).then(res => {
        this.menuLoading = false;
        if(res.success){
            this.$refs.permTree.setCheckedKeys(res.data);
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.Id != undefined) {
            updateRole(this.form).then(res => {
              if(res.success){
                 this.open = false;
                 this.getList();
                 this.msgSuccess("修改成功")
             }else{
               this.msgError(res.msg)
             }
            });
          } else {
             addRoleModel(this.form).then(res=>{
             if(res.success){
                 this.open = false;
                 this.getList();
                 this.msgSuccess("新增操作成功")
             }else{
               this.msgError(res.msg)
             }
         }).catch(ex=>{
               this.msgError(ex)
         })
          }
        }
      });
    },
    /** 获取所有权限菜单 */
    getAllMenus () {
      getAllMenu().then(res => {
        if (res.success) {
          this.MenuTreeData = res.data;  //所有权限菜单
        }
      }).catch(ex => {
        this.msgError(ex.message)
      })
    },

    /** 提交按钮（数据权限） */
    submitRolePerm () {
        let pids = this.$refs.permTree.getCheckedKeys(); // 获取选中的所有菜单id
        console.log(this.currentRole.Id,pids)
        UpdatePermission(this.currentRole.Id,pids).then(res=>{
          if(res.success){
             this.treecancel()
             this.msgSuccess("操作成功")
          }
          else{
            this.msgError(res.msg)
          }
        }).catch(ex=>{this.msgError(ex)})
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const roleIds = row.roleId || this.ids;
      this.$confirm(
        '是否确认删除角色编号为"' + roleIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function () {
          //return delRole(roleIds);
        })
        .then(() => {
          // this.getList();
          // this.msgSuccess("删除成功");
        });
    },

  }
};
</script>
